package com.doge.walknovel.push


import android.content.Intent
import com.doge.walknovel.analysis.analysisPushClicked
import com.doge.walknovel.api.*
import com.doge.walknovel.business.WebActivity
import com.doge.walknovel.business.home.profile.topup.TopUpActivity
import com.doge.walknovel.business.home.profile.topup.TopUpRefer
import com.doge.walknovel.business.novel.NovelDetailActivity
import com.doge.walknovel.business.novel.NovelRefer
import com.doge.walknovel.core.account.AccountHelper
import com.doge.walknovel.core.account.AccountHelper.self
import com.doge.walknovel.utils.*
import com.google.android.gms.tasks.OnCanceledListener
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.Task
import com.google.firebase.messaging.FirebaseMessaging

object PushHelper {
    private const val TYPE_WEB = "web"
    const val TYPE_NOVEL_DETAIL = "novelDetail"
    private const val TYPE_RECHARGE = "recharge"
    private val key: String get() = "t${self.memberId}"
    private const val folder = "firebase"
    private var lastRequest: String? = null

    private fun touchDuplicate(token: String?): Boolean {
        val requestKey = "${self.memberId}#$token"
        if (lastRequest.isNullOrEmpty()) {
            lastRequest = requestKey
            return false
        }
        if (lastRequest != requestKey) {
            lastRequest = requestKey
            return false
        }
        return true
    }

    fun handleToken(token: String?) {
        log("PushHelper handleToken token $token")
        if (token.isNullOrEmpty()) {
            log("PushHelper handleToken firebase sdk provide token is NullOrEmpty")
            return // 没token不上传
        }
        if (touchDuplicate(token)) {
            log("PushHelper handleToken touchDuplicate token already uploaded.")
            return // token曾经上传过了
        }
        val lastToken = spReadString(key, "", folder)
        if (lastToken == token) {
            log("PushHelper handleToken token already uploaded.")
            return  // token已经上传过了
        }

        log("PushHelper handleToken start upload to server $token")
        api
            .pushUpdateToken(token)
            .compose(ApiResultComposeTransformer())
            .subscribeOnIO()
            .observeOnWork()
            .subscribe(object : ObserverAdapter<Any?>() {
                override fun onNext(t: Any?) {
                    log("PushHelper handleToken upload to server onNext ")
                    spWrite(key, token, folder)
                }

                override fun onError(e: Throwable) {
                    lastRequest = null
                }
            })
    }

    fun check() {
        log("PushHelper check firebaseToken by userToken ${AccountHelper.token}")
        FirebaseMessaging.getInstance().token
            .addOnCompleteListener(listener)
            .addOnFailureListener(failureListener)
            .addOnCanceledListener(cancelledListener)
    }

    private val cancelledListener = OnCanceledListener {
        log("PushHelper FirebaseInstanceId onCancelled")
    }
    private val failureListener = OnFailureListener {
        log("PushHelper FirebaseInstanceId onFailure")
        it.printStackTrace()
    }
    private val listener = object : OnCompleteListener<String> {
        override fun onComplete(task: Task<String>) {
            log("PushHelper FirebaseInstanceId onComplete [${task.isSuccessful}][${task.exception}]")
            if (!task.isSuccessful) return
            handleToken(task.result) // Get new Instance ID token
        }
    }

    fun handleIntent(intent: Intent?): Boolean {
        val type = intent?.getStringExtra("type")
        log("PushHelper handleIntent $type")
        if (type?.isNotEmpty() == true) {
            analysisPushClicked(type)
        }
        return when (type) {
            TYPE_WEB -> {
                WebActivity.start(
                    Activities.top ?: appContext,
                    intent.getStringExtra("linkUrl")
                )
                true
            }
            TYPE_NOVEL_DETAIL -> {
                NovelDetailActivity.start(
                    Activities.top ?: appContext,
                    intent.getStringExtra("novelId")?.toIntOrNull(),
                    NovelRefer.push
                )
                true
            }
            TYPE_RECHARGE -> {
                TopUpActivity.start(Activities.top ?: appContext, TopUpRefer.push)
                true
            }
            else -> false
        }
    }
}